import urllib
import BeautifulSoup

class Querier:
    def __init__(self):
        self.shortName = "im"
        self.longName = "Industrial-Music.com"
        self.provides = ['album_front_small']

        self.baseURL = "http://www.industrial-music.com/search.php?type=title&"
        self.artURL = "http://www.industrial-music.com/images/product/"
        self.metURL = "http://metropolis-records.com/cdcover.php?num="

    def process(self, item):
        ret = []
        small=None
        baseArtist = item.artist
        quoteAlbum=urllib.quote (item.album.encode("UTF-8"))

        data = urllib.urlopen (self.baseURL+"terms=%s" % quoteAlbum).read ()
        soup = BeautifulSoup.BeautifulSoup (data)
        m = soup("div", {"id":"content"})
        try:
            table_area = m[0]("tr", {"valign":"middle"})
        except IndexError:
            return ret
        for e in table_area:
            art = e("strong")[0].string
            try:
                alb = e("a")[1].string
            except Exception:
                return ret
            tmp = str (e("a")[1])
            albumID = tmp[tmp.index("prodnum=")+8:tmp.index("&")]
            if art.lower() == baseArtist.lower():
                if not albumID.startswith ("MET"):
                    small = "%s%s-160.jpg" % (self.artURL, albumID.replace("+", ""))
            else:
                try:
                    id=albumID[albumID.index("+")+1:].replace ("DVD", "")
                except Exception:
                    return ret
                small = "%s%s" % (self.metURL, id)
            ret.append(small)
        return ret
